package com.yy.wga.goods.service.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.yy.wga.common.core.dto.PageBean;
import com.yy.wga.common.core.enmus.EUserGrade;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.common.util.common.StringUtils;
import com.yy.wga.common.util.mapping.BeansUtils;
import com.yy.wga.common.web.intereceptor.RequestHolder;
import com.yy.wga.goods.feign.request.ResourceGoodsCategoryReq;
import com.yy.wga.goods.feign.response.*;
import com.yy.wga.goods.service.api.bo.GetPromoteGoodsTaskV2BO;
import com.yy.wga.goods.service.entity.bo.GoodsIdBO;
import com.yy.wga.goods.service.entity.pojo.GoodsHeadSupplierInfoDO;
import com.yy.wga.goods.service.entity.pojo.ResourceGoodsCategoryDO;
import com.yy.wga.goods.service.entity.pojo.ResourceGoodsCategoryExtendDO;
import com.yy.wga.goods.service.mapper.GoodsHeadSupplierInfoMapper;
import com.yy.wga.goods.service.service.ResourceGoodsCategoryExtendService;
import com.yy.wga.goods.service.service.ResourceGoodsCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ResourceGoodsCategoryManager {

    @Resource
    private ResourceGoodsCategoryService resourceGoodsCategoryService;
    @Resource
    private ResourceGoodsCategoryExtendService resourceGoodsCategoryExtendService;
    @Resource
    private GoodsHeadSupplierInfoMapper goodsHeadSupplierInfoMapper;


    public void addCategory(ResourceGoodsCategoryReq.AddCategory request) {
        ResourceGoodsCategoryDO categoryDO = new ResourceGoodsCategoryDO();
        BeanUtils.copyProperties(request, categoryDO);
        categoryDO.setStatus(1);
        categoryDO.setAppKey(RequestHolder.getAppKey());
        resourceGoodsCategoryService.save(categoryDO);
    }

    public void updateCategory(ResourceGoodsCategoryReq.UpdateCategory request) {
        Integer id = request.getId();
        ResourceGoodsCategoryDO categoryDO = resourceGoodsCategoryService.getById(id);
        if (Objects.isNull(id)) {
            throw new BusinessException("分类不存在");
        }
        BeanUtils.copyProperties(request, categoryDO);
        resourceGoodsCategoryService.updateById(categoryDO);
    }

    public void deleteCategory(ResourceGoodsCategoryReq.DeleteCategory request) {
        List<Integer> ids = request.getIds();
        resourceGoodsCategoryService.removeByIds(ids);
        resourceGoodsCategoryExtendService.remove(new LambdaQueryWrapper<ResourceGoodsCategoryExtendDO>().in(ResourceGoodsCategoryExtendDO::getCategoryId, ids));
    }

    public List<GetResourceGoodsCategoryResponse> listCategory() {
        String appKey = RequestHolder.getAppKey();
        List<ResourceGoodsCategoryDO> list = resourceGoodsCategoryService.list(new LambdaQueryWrapper<ResourceGoodsCategoryDO>().eq(ResourceGoodsCategoryDO::getAppKey, appKey).orderByDesc(ResourceGoodsCategoryDO::getSort));
        List<GetResourceGoodsCategoryResponse> resultList = BeansUtils.mapList(list, GetResourceGoodsCategoryResponse.class);
        return resultList;
    }

    public List<GetResourceGoodsCategoryResponse> listAvailableCategory() {
        String appKey = RequestHolder.getAppKey();
        List<ResourceGoodsCategoryDO> list = resourceGoodsCategoryService.list(new LambdaQueryWrapper<ResourceGoodsCategoryDO>().eq(ResourceGoodsCategoryDO::getAppKey, appKey).eq(ResourceGoodsCategoryDO::getStatus, 1).eq(ResourceGoodsCategoryDO::getHomepageDisplay, 1).orderByDesc(ResourceGoodsCategoryDO::getSort));
        List<GetResourceGoodsCategoryResponse> resultList = BeansUtils.mapList(list, GetResourceGoodsCategoryResponse.class);
        return resultList;

    }

    public void sortCategory(ResourceGoodsCategoryReq.SortCategory request) {
        List<ResourceGoodsCategoryReq.IdSort> dataList = request.getDataList();
        List<ResourceGoodsCategoryDO> categoryList = dataList.stream().map(data -> {
            ResourceGoodsCategoryDO categoryDO = new ResourceGoodsCategoryDO();
            categoryDO.setId(Long.valueOf(data.getId()));
            categoryDO.setSort(data.getSort());
            return categoryDO;
        }).collect(Collectors.toList());
        resourceGoodsCategoryService.updateBatchById(categoryList);
    }

    public void changeCategoryStatus(ResourceGoodsCategoryReq.ChangeCategoryStatus request) {
        List<ResourceGoodsCategoryReq.IdStatus> dataList = request.getDataList();
        List<ResourceGoodsCategoryDO> categoryList = dataList.stream().map(data -> {
            ResourceGoodsCategoryDO categoryDO = new ResourceGoodsCategoryDO();
            categoryDO.setId(Long.valueOf(data.getId()));
            categoryDO.setStatus(data.getStatus());
            return categoryDO;
        }).collect(Collectors.toList());
        resourceGoodsCategoryService.updateBatchById(categoryList);
    }

    public void changeHomepageDisplay(ResourceGoodsCategoryReq.ChangeHomepageDisplay request) {
        ResourceGoodsCategoryDO categoryDO = new ResourceGoodsCategoryDO();
        categoryDO.setId(Long.valueOf(request.getId()));
        categoryDO.setHomepageDisplay(request.getHomepageDisplay());
        resourceGoodsCategoryService.updateById(categoryDO);
    }

    public void changeSupportSubsidyAmount(ResourceGoodsCategoryReq.ChangeSupportSubsidyAmount request) {
        ResourceGoodsCategoryDO categoryDO = new ResourceGoodsCategoryDO();
        categoryDO.setId(Long.valueOf(request.getId()));
        categoryDO.setSupportSubsidyAmount(request.getSupportSubsidyAmount());
        resourceGoodsCategoryService.updateById(categoryDO);
    }


    public void addGoods(ResourceGoodsCategoryReq.AddGoods request) {
        Integer categoryId = request.getCategoryId();
        String appKey = RequestHolder.getAppKey();
        // 获取该品类最高的sort
        Integer maxSort = resourceGoodsCategoryExtendService.getMaxSort(appKey, categoryId);
        if (Objects.isNull(maxSort)) {
            maxSort = 0;
        }

        List<ResourceGoodsCategoryExtendDO> saveList = new ArrayList<>();
        List<ResourceGoodsCategoryReq.Goods> goodsList = request.getGoodsList();
        for (ResourceGoodsCategoryReq.Goods goods : goodsList) {
            if (Objects.nonNull(resourceGoodsCategoryExtendService.getResourceGoodsCategoryExtend(appKey, categoryId, goods.getShopAppid(), goods.getSpuId()))) {
                continue;
            }
            ResourceGoodsCategoryExtendDO categoryExtendDO = new ResourceGoodsCategoryExtendDO();
            categoryExtendDO.setCategoryId(categoryId);
            categoryExtendDO.setAppKey(appKey);
            categoryExtendDO.setSpuId(goods.getSpuId());
            categoryExtendDO.setShopAppid(goods.getShopAppid());
            categoryExtendDO.setSort(++maxSort);


            List<GoodsInfoResp> goodsInfoResps = GetPromoteGoodsTaskV2BO.builder()
                    .goodsIdBOList(Arrays.asList(new GoodsIdBO(goods.getShopAppid(), goods.getSpuId())))
                    .userGrade(EUserGrade.COMMON)
                    .appKey(RequestHolder.getAppKey())
                    .playType(1)
                    .useDb(true)
                    .build().execute();
            if (CollectionUtil.isEmpty(goodsInfoResps)) {
                categoryExtendDO.setTitle(goodsInfoResps.get(0).getTitle());
            } else {
                categoryExtendDO.setTitle(StrUtil.EMPTY);
            }

            saveList.add(categoryExtendDO);
        }

        // 检查是否在配置中
        if (CollectionUtil.isNotEmpty(saveList)) {
            resourceGoodsCategoryExtendService.saveBatch(saveList);
        }
    }

    public void deleteGoods(ResourceGoodsCategoryReq.DeleteGoods request) {
        List<ResourceGoodsCategoryReq.Goods> goodsList = request.getGoodsList();
        List<String> shopAppIds = goodsList.stream().map(ResourceGoodsCategoryReq.Goods::getShopAppid).collect(Collectors.toList());
        List<String> spuIds = goodsList.stream().map(ResourceGoodsCategoryReq.Goods::getSpuId).collect(Collectors.toList());
        resourceGoodsCategoryExtendService.remove(new LambdaQueryWrapper<ResourceGoodsCategoryExtendDO>().eq(ResourceGoodsCategoryExtendDO::getAppKey, RequestUserHolder.getAppKey()).eq(ResourceGoodsCategoryExtendDO::getCategoryId, request.getCategoryId()).in(ResourceGoodsCategoryExtendDO::getShopAppid, shopAppIds).in(ResourceGoodsCategoryExtendDO::getSpuId, spuIds));
    }

    public PageBean<GetPageCategoryGoodsResp> pageGoods(ResourceGoodsCategoryReq.PageGoods request) {
        String appKey = RequestHolder.getAppKey();

        PageHelper.startPage(request.getPageNum(), request.getPageSize());

        List<ResourceGoodsCategoryExtendDO> extendList = resourceGoodsCategoryExtendService.list(new LambdaQueryWrapper<ResourceGoodsCategoryExtendDO>()
                .eq(ResourceGoodsCategoryExtendDO::getAppKey, appKey)
                .eq(ResourceGoodsCategoryExtendDO::getCategoryId, request.getCategoryId())
                .like(StringUtils.isNotBlank(request.getKeyword()), ResourceGoodsCategoryExtendDO::getTitle, request.getKeyword())
                .orderByDesc(ResourceGoodsCategoryExtendDO::getSort));
        Map<String, ResourceGoodsCategoryExtendDO> extendDOMap = extendList.stream().collect(Collectors.toMap(item -> {
            return String.valueOf(item.getShopAppid() + "_" + item.getSpuId());
        }, Function.identity()));


        // 获取商品信息
        List<GoodsIdBO> goodsIdBOList = extendList.stream().map(record -> {
            return GoodsIdBO.builder().shopAppid(record.getShopAppid()).productId(record.getSpuId()).build();
        }).collect(Collectors.toList());

        GetPromoteGoodsTaskV2BO getPromoteGoodsTaskBO = GetPromoteGoodsTaskV2BO.builder()
                .goodsIdBOList(goodsIdBOList)
                .userGrade(RequestHolder.getUserGrade())
                .appKey(RequestHolder.getAppKey())
                .playType(1)
                .useDb(true)
                .build();

        List<GoodsInfoResp> goodsInfoRespList = getPromoteGoodsTaskBO.execute();

        List<GetPageCategoryGoodsResp> respList = BeansUtils.mapList(goodsInfoRespList, GetPageCategoryGoodsResp.class);
        for (GetPageCategoryGoodsResp resp : respList) {
            String key = resp.getShopAppid() + "_" + resp.getSpuId();
            ResourceGoodsCategoryExtendDO extendDO = extendDOMap.get(key);
            if (Objects.nonNull(extendDO)) {
                resp.setSort(extendDO.getSort());
                resp.setRecommendReason(extendDO.getRecommendReason());
                resp.setSubsidyAmount(extendDO.getSubsidyAmount());
            } else {
                resp.setSort(0);
                resp.setRecommendReason(StringUtils.EMPTY);
                resp.setSubsidyAmount(0);
            }
        }

        PageBean<GetPageCategoryGoodsResp> pageBean = new PageBean<>();
        pageBean.setPageInfo(extendList);
        pageBean.setList(respList);
        return pageBean;

    }


    public List<GetAllCategoryGoodsResp> allCategoryGoods(ResourceGoodsCategoryReq.AllGoods request) {
        String appKey = RequestHolder.getAppKey();

        List<ResourceGoodsCategoryExtendDO> extendList = resourceGoodsCategoryExtendService
                .list(new LambdaQueryWrapper<ResourceGoodsCategoryExtendDO>()
                        .eq(ResourceGoodsCategoryExtendDO::getAppKey, appKey)
                        .eq(ResourceGoodsCategoryExtendDO::getCategoryId, request.getCategoryId())
                        .like(StringUtils.isNotBlank(request.getKeyword()), ResourceGoodsCategoryExtendDO::getTitle, request.getKeyword())
                        .orderByDesc(ResourceGoodsCategoryExtendDO::getSort));

        return BeansUtils.mapList(extendList, GetAllCategoryGoodsResp.class);
    }


    public void sortGoods(ResourceGoodsCategoryReq.SortGoods request) {
        String appKey = RequestHolder.getAppKey();
        Integer categoryId = request.getCategoryId();
        List<ResourceGoodsCategoryReq.GoodsSort> dataList = request.getDataList();

        List<ResourceGoodsCategoryExtendDO> updateList = new ArrayList<>();
        dataList.forEach(data -> {
            ResourceGoodsCategoryExtendDO extend = resourceGoodsCategoryExtendService.getResourceGoodsCategoryExtend(appKey, categoryId, data.getShopAppid(), data.getSpuId());
            if (Objects.nonNull(extend)) {
                extend.setSort(data.getSort());
                updateList.add(extend);
            }
        });
        if (CollectionUtil.isNotEmpty(updateList)) {
            resourceGoodsCategoryExtendService.updateBatchById(updateList);
        }
    }

    public void setRecommendReason(ResourceGoodsCategoryReq.SetRecommendReason request) {
        String appKey = RequestHolder.getAppKey();
        Integer categoryId = request.getCategoryId();
        ResourceGoodsCategoryExtendDO extend = resourceGoodsCategoryExtendService.getResourceGoodsCategoryExtend(appKey, categoryId, request.getShopAppid(), request.getSpuId());
        if (Objects.nonNull(extend)) {
            extend.setRecommendReason(request.getRecommendReason());
            resourceGoodsCategoryExtendService.updateById(extend);
        }
    }

    public void setSubsidyAmount(ResourceGoodsCategoryReq.SetSubsidyAmount request) {
        String appKey = RequestHolder.getAppKey();
        Integer categoryId = request.getCategoryId();
        ResourceGoodsCategoryDO resourceGoodsCategoryDO = resourceGoodsCategoryService.getById(categoryId);
        if (Objects.isNull(resourceGoodsCategoryDO)) {
            throw new BusinessException("分类不存在");
        }
        if (Objects.equals(resourceGoodsCategoryDO.getSupportSubsidyAmount(), 0)) {
            throw new BusinessException("分类不支持每单补贴配置");
        }
        ResourceGoodsCategoryExtendDO extend = resourceGoodsCategoryExtendService.getResourceGoodsCategoryExtend(appKey, categoryId, request.getShopAppid(), request.getSpuId());
        if (Objects.nonNull(extend)) {
            extend.setSubsidyAmount(request.getSubsidyAmount());
            resourceGoodsCategoryExtendService.updateById(extend);
        }
    }


    public PageBean<GoodsInfoResp> getHeadSupplierGoodsV2(ResourceGoodsCategoryReq.GetHeadSupplierGoodsReqV2 request) {

        LambdaQueryWrapper<GoodsHeadSupplierInfoDO> queryWrapper = new LambdaQueryWrapper<GoodsHeadSupplierInfoDO>()
                .select(GoodsHeadSupplierInfoDO::getSpuId, GoodsHeadSupplierInfoDO::getShopAppid)
                .eq(GoodsHeadSupplierInfoDO::getDeleted, 0)
                .eq(GoodsHeadSupplierInfoDO::getAppKey, RequestUserHolder.getAppKey())
                .like(StringUtils.isNotBlank(request.getKeyword()), GoodsHeadSupplierInfoDO::getTitle, request.getKeyword())
                .orderByDesc(GoodsHeadSupplierInfoDO::getId);
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<GoodsHeadSupplierInfoDO> headSupplierInfoLists = goodsHeadSupplierInfoMapper.selectList(queryWrapper);
        List<GoodsIdBO> goodsIdBOList = headSupplierInfoLists.stream().map(item -> {
            return new GoodsIdBO(item.getSpuId(), item.getShopAppid());
        }).collect(Collectors.toList());

        // 查看合作商品 使用定向计划
        GetPromoteGoodsTaskV2BO getPromoteGoodsTaskBO = GetPromoteGoodsTaskV2BO.builder()
                .goodsIdBOList(goodsIdBOList)
                .userGrade(RequestUserHolder.getUserGrade())
                .appKey(RequestUserHolder.getAppKey())
                .playType(1)
                .useDb(true)
                .build();

        List<GoodsInfoResp> respList = getPromoteGoodsTaskBO.execute();


        PageBean<GoodsInfoResp> pageBean = new PageBean<>();
        pageBean.setPageInfo(headSupplierInfoLists);
        pageBean.setList(respList);
        return pageBean;
    }
}
